package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.mapper.PublishInfoMapper;
import com.tanhua.server.pojo.PublishInfo;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Movements;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.PicUploadResult;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Service
public class MovementsService {

    @Reference(version = "1.0.0")
    QuanZiApi quanZiApi;

    @Autowired
    private HuaWeiService huaWeiService;

    @Autowired
    private PublishInfoMapper publishInfoMapper;

    @Autowired
    PicUploadService picUploadService;

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Reference(version = "1.0.0")
    VisitorsApi visitorsApi;

    /**
     * 发布朋友圈
     *
     * @param textContent
     * @param location
     * @param latitude
     * @param longitude
     * @param multipartFile
     * @return
     */
    public String saveMovements(String textContent, String location, String latitude, String longitude, MultipartFile[] multipartFile) {
        User user = UserThreadLocal.get();


        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        //图片上传
        List<String> imageUrls = new ArrayList<>();  //保存上传后的图片名


        for (MultipartFile file : multipartFile) {
            PicUploadResult uploadResult = picUploadService.upload(file);
            imageUrls.add(uploadResult.getName());
        }
        publish.setMedias(imageUrls);


        String publishId = quanZiApi.savePublish(publish);

        //审核状态，1为待审核，2为自动审核通过，3为待人工审核，4为人工审核拒绝，5为人工审核通过，6为自动审核拒绝
        String imageResult = huaWeiService.auditImage(imageUrls.toArray(new String[]{}));
        String textResult = huaWeiService.auditText(publish.getText());
        PublishInfo publishInfo = new PublishInfo();
        publishInfo.setPublishId(publishId);
        publishInfo.setUserId(publish.getUserId());
        publishInfo.setTopState(1);
        publishInfo.setCreateDate(System.currentTimeMillis());
        publishInfo.setUpdated(publishInfo.getCreated());
        if (imageResult.equals("block") ||
                textResult.equals("block")) {
            //自动审核通过
            publishInfo.setState("6");
            this.publishInfoMapper.insert(publishInfo);
            return publishId;
        }

        if (imageResult.equals("review") ||
                textResult.equals("review")
        ) {
            publishInfo.setState("3");
            this.publishInfoMapper.insert(publishInfo);
            return publishId;
        }

        if (imageResult.equals("pass") &&
                textResult.equals("pass")
        ) {
            publishInfo.setState("2");
            this.publishInfoMapper.insert(publishInfo);
        }

        return publishId;


    }


    private PageResult queryPublishList(User user, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        Long userId = null;          //默认查询推荐动态

        PageInfo<Publish> pageInfo = null;


        if (null == user) {
            //查询推荐动态
            String key = "QUANZI_PUBLISH_RECOMMEND_" + UserThreadLocal.get().getId();
            String value = this.redisTemplate.opsForValue().get(key);
            if (StringUtils.isNotEmpty(value)) {
                //命中了数据
                String[] pids = StringUtils.split(value, ",");
                int startIndex = (page - 1) * pageSize;
                if (startIndex < pids.length) {
                    int endIndex = startIndex + pageSize - 1;
                    if (endIndex >= pids.length) {
                        endIndex = pids.length - 1;
                    }
                    List<Long> pidList = new ArrayList<>();
                    for (int i = startIndex; i <= endIndex; i++) {
                        pidList.add(Long.valueOf(pids[i]));
                    }

                    List<Publish> publishList = this.quanZiApi.queryPublishByPids(pidList);
                    pageInfo = new PageInfo<>();
                    pageInfo.setRecords(publishList);
                }
            }

        }


        if (pageInfo == null) {
            if (user != null) {
                //查询好友动态
                userId = user.getId();
            }
            pageInfo = this.quanZiApi.queryPublishList(userId, page, pageSize);
        }


        user = UserThreadLocal.get();       //查询完成后，依然需要获取到当前的登陆用户

        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);

        List<Publish> records = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            //没有查询到动态数据
            return pageResult;
        }

        List<Movements> movementsList = fillValueToMovements(records);

        pageResult.setItems(movementsList);
        return pageResult;
    }

    /**
     * 查询推荐朋友圈
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        return this.queryPublishList(null, page, pageSize);
    }

    /**
     * 查询朋友圈
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryUserPublishList(Integer page, Integer pageSize) {
        return this.queryPublishList(UserThreadLocal.get(), page, pageSize);
    }

    /**
     * 点赞
     *
     * @param publishId
     * @return
     */
    public Long likeComment(String publishId) {
        User user = UserThreadLocal.get();

        boolean bool = this.quanZiApi.saveLikeComment(user.getId(), publishId);
        if (!bool) {
            //保存失败
            return null;
        }

        //保存成功，获取点赞数,并缓存到redis中
        Long likeCount = 0L;
        String likeCommentKey = "QUANZI_COMMENT_LIKE_" + publishId;
        if (!this.redisTemplate.hasKey(likeCommentKey)) {

            //之前如果未缓存过该圈子的点赞数，则在mongodb中查询该圈子的点赞数，并保存到redis中
            Long count = this.quanZiApi.queryCommentCount(publishId, 1);
            likeCount = count;
            this.redisTemplate.opsForValue().set(likeCommentKey, String.valueOf(likeCount));
        } else {
            //之前如果缓存过该圈子的点赞数，则将点赞数量加1
            likeCount = this.redisTemplate.opsForValue().increment(likeCommentKey);
        }

        //记录当前用户已经点赞过
        String likeUserCommentKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(likeUserCommentKey, "1");

        return likeCount;
    }

    /**
     * 取消点赞
     *
     * @param publishId
     * @return
     */
    public Long disLikeComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean bool = this.quanZiApi.removeComment(user.getId(), publishId, 1);
        if (!bool) {
            return null;
        }

        //更新redis中的喜欢数（减1）
        String likeCommentKey = "QUANZI_COMMENT_LIKE_" + publishId;
        Long count = this.redisTemplate.opsForValue().decrement(likeCommentKey);

        //从redis中删除当前用户的喜欢记录
        String userKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.delete(userKey);

        return count;
    }

    /**
     * 喜欢
     *
     * @param publishId
     * @return
     */

    public Long loveComment(String publishId) {
        User user = UserThreadLocal.get();

        boolean bool = this.quanZiApi.saveLoveComment(user.getId(), publishId);
        if (!bool) {
            //保存失败
            return null;
        }

        //保存成功，获取喜欢数,并缓存到redis中
        Long loveCount = 0L;
        String loveCommentKey = "QUANZI_COMMENT_LOVE_" + publishId;
        if (!this.redisTemplate.hasKey(loveCommentKey)) {

            //之前如果未缓存过该圈子的喜欢数，则在mongodb中查询该圈子的喜欢数，并保存到redis中
            Long count = this.quanZiApi.queryCommentCount(publishId, 3);
            loveCount = count;
            this.redisTemplate.opsForValue().set(loveCommentKey, String.valueOf(loveCount));
        } else {
            //之前如果缓存过该圈子的点赞数，则将点赞数量加1
            loveCount = this.redisTemplate.opsForValue().increment(loveCommentKey);
        }

        //记录当前用户已经点赞过
        String loveUserCommentKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(loveUserCommentKey, "1");

        return loveCount;
    }

    /**
     * 取消喜欢
     *
     * @param publishId
     * @return
     */
    public Long unLoveComment(String publishId) {

        User user = UserThreadLocal.get();
        boolean bool = this.quanZiApi.removeComment(user.getId(), publishId, 3);
        if (!bool) {
            return null;
        }

        //更新redis中的喜欢数（减1）
        String loveCommentKey = "QUANZI_COMMENT_LOVE_" + publishId;
        Long count = this.redisTemplate.opsForValue().decrement(loveCommentKey);

        //从redis中删除当前用户的喜欢记录
        String userKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.delete(userKey);

        return count;
    }

    /**
     * 查询动态详情
     *
     * @param publishId
     * @return
     */
    public Movements queryMovementsById(String publishId) {

        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (null == publish) {
            return null;
        }

        //查询到动态数据，将publish转换成Movements对象返回
        List<Movements> movementsList = this.fillValueToMovements(Arrays.asList(publish));
        return movementsList.get(0);
    }


    /**
     * 填充圈子数据
     *
     * @param records
     * @return
     */
    private List<Movements> fillValueToMovements(List<Publish> records) {

        User user = UserThreadLocal.get();

        List<Movements> movementsList = new ArrayList<>();
        for (Publish record : records) {
            Movements movements = new Movements();

            movements.setId(record.getId().toHexString());
            movements.setImageContent(record.getMedias().toArray(new String[]{}));
            movements.setTextContent(record.getText());
            movements.setUserId(record.getUserId());
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));

            movementsList.add(movements);
        }

        List<Long> userIds = new ArrayList<>();
        for (Movements movements : movementsList) {
            if (!userIds.contains(movements.getId())) {
                userIds.add(movements.getUserId());
            }

        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);
        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfos) {
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    movements.setAge(userInfo.getAge());
                    movements.setAvatar(userInfo.getLogo());
                    movements.setGender(userInfo.getSex().name().toLowerCase());
                    movements.setNickname(userInfo.getNickName());
                    movements.setTags(StringUtils.split(userInfo.getTags(), ','));
                    movements.setCommentCount(10); //TODO 评论数
                    movements.setDistance("1.2公里"); //TODO 距离

                    // movements.setHasLiked(1); //TODO 是否点赞（1是，0否）
                    // movements.setLikeCount(100); //TODO 点赞数
                    movements.setHasLiked(this.redisTemplate.hasKey("QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + movements.getId()) ? 1 : 0);

                    String likeCommentKey = "QUANZI_COMMENT_LIKE_" + movements.getId();
                    String value = this.redisTemplate.opsForValue().get(likeCommentKey);
                    if (StringUtils.isNotEmpty(value)) {
                        movements.setLikeCount(Integer.valueOf(value)); //点赞数
                    } else {
                        movements.setLikeCount(0);  //点赞数
                    }

                    // movements.setHasLoved(0); //TODO 是否喜欢（1是，0否）
                    // movements.setLoveCount(80); //TODO 喜欢数
                    String loveUserCommentKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + movements.getId();
                    movements.setHasLoved(this.redisTemplate.hasKey(loveUserCommentKey) ? 1 : 0);      //是否喜欢

                    String loveCommentKey = "QUANZI_COMMENT_LOVE_" + movements.getId();
                    String loveValue = this.redisTemplate.opsForValue().get(loveCommentKey);
                    if (StringUtils.isNotEmpty(loveValue)) {
                        movements.setLoveCount(Integer.valueOf(loveValue)); //点赞数
                    } else {
                        movements.setLoveCount(0);  //点赞数
                    }
                    break;
                }
            }
        }

        return movementsList;
    }

    /**
     * 查询最近的访客
     *
     * @return
     */
    public List<VisitorsVo> queryVisitorsList() {

        User user = UserThreadLocal.get();
        List<Visitors> visitors = null;
        String redisKey = "visitor_date_" + user.getId();
        String value = this.redisTemplate.opsForValue().get(redisKey);

        if (StringUtils.isEmpty(value)) {
            //如果以前没有查看过"我的访客"，则显示最近的5个访问信息
            visitors = this.visitorsApi.topVisitor(user.getId(), 5);
        } else {
            //如果以前查看过"我的访客"，则显示上一次查看之后的访客信，没有就不显示
            visitors = this.visitorsApi.topVisitor(user.getId(), Long.valueOf(value));
        }

        if (CollectionUtils.isEmpty(visitors)) {
            return Collections.emptyList(); //如果最近没有访客信息，要返回一个空集合，防止前端报错
        }

        //获取访客id，用于后面完善访客信息
        List<Long> userIds = new ArrayList<>();
        for (Visitors visitor : visitors) {
            userIds.add(visitor.getVisitorUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

        List<VisitorsVo> visitorsVoList = new ArrayList<>();
        for (Visitors visitor : visitors) {
            for (UserInfo userInfo : userInfoList) {
                if (visitor.getVisitorUserId().longValue() == userInfo.getUserId().longValue()) {
                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ","));
                    visitorsVo.setFateValue(visitor.getScore().intValue());
                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }
        return visitorsVoList;
    }

    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        PageInfo<Publish> albumPageInfo = this.quanZiApi.queryAlbumList(userId, page, pageSize);
        List<Publish> records = albumPageInfo.getRecords();

        if (CollectionUtils.isEmpty(records)) {
            return pageResult;
        }

        //圈子数据填充
        List<Movements> movementsList = this.fillValueToMovements(records);
        pageResult.setItems(movementsList);

        return pageResult;
    }
}
